package com.uniledger.exchange.mine;


import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.rohit.recycleritemclicksupport.RecyclerItemClickSupport;
import com.uniledger.commonlib.lazy.LazyFragmentPagerAdapter;
import com.uniledger.commonlib.util.DisplayUtil;
import com.uniledger.exchange.R;
import com.uniledger.exchange.UniApp;
import com.uniledger.exchange.bank.MangerBankActivity;
import com.uniledger.exchange.base.fragment.BaseFragment;
import com.uniledger.exchange.home.Glide4Engine;
import com.uniledger.exchange.home.scheme.ContactActivity;
import com.uniledger.exchange.login.Admin;
import com.uniledger.exchange.mine.scheme.HelpCenterActivity;
import com.uniledger.exchange.mine.scheme.HistoryActivity;
import com.uniledger.exchange.mine.scheme.SettingActivity;
import com.uniledger.exchange.model.rx.RxException;
import com.uniledger.exchange.model.rx.RxSchedulers;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.functions.Consumer;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

import static android.app.Activity.RESULT_OK;

/**
 * 我的页面
 */
public class MineFragment extends BaseFragment implements LazyFragmentPagerAdapter.Laziable, EasyPermissions.PermissionCallbacks {

    private static final int REQUEST_CODE_CHOOSE = 23;
    public static final int REQUEST_CODE_OUT = 0X04;

    private static final String[] READ_AND_WRITE_STORAGE =
            {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static final int RC_READ_AND_WRITE_STORAGE = 124;


    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;

    @BindView(R.id.recycler_my_center)
    RecyclerView recyclerCenter;

    MyCenterAdapter adapter;

    public MineFragment() {
        // Required empty public constructor
    }

    public static MineFragment newInstance(String param1, String param2) {
        MineFragment fragment = new MineFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());

        recyclerCenter.setLayoutManager(manager);

        HorizontalDividerItemDecoration decoration = new HorizontalDividerItemDecoration.Builder(getActivity())
                .size(DisplayUtil.dip2px(getActivity(),16))
                .build();

        recyclerCenter.addItemDecoration(decoration);

        adapter = new MyCenterAdapter(getActivity());
        recyclerCenter.setAdapter(adapter);
        adapter.addData();

        RecyclerItemClickSupport.addTo(recyclerCenter)
                .setOnItemClickListener(new RecyclerItemClickSupport.OnItemClickListener() {
                    @Override
                    public void onItemClicked(RecyclerView recyclerView, int position, View v) {

                        switch (position) {
                            case 0:
                                break;
                            case 1:
                                HistoryActivity.start(getActivity());
                                break;
                            case 2:
                                ContactActivity.start(getActivity());
                                break;
                            case 3:
                                MangerBankActivity.start(getActivity());
                                break;
//                            case 4:
//                                HelpCenterActivity.start(getActivity());
//                                break;
                            case 4:
                                SettingActivity.start(getActivity());
                                break;
                            default:
                                break;
                        }


                    }
                });

        UniApp.getDb().adminDao()
                .loadAdmin(123)
                .compose(RxSchedulers.io_main())
                .subscribe(new Consumer<Admin>() {
                    @Override
                    public void accept(Admin admin) throws Exception {
                        adapter.updateUserInfo(admin);
                    }
                }, new RxException<>(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                }));

    }

    /**
     * 判断是否有读写文件夹权限
     *
     * @return
     */
    private boolean hasReadAndWritePermissions() {
        return EasyPermissions.hasPermissions(getActivity(), READ_AND_WRITE_STORAGE);
    }

    @AfterPermissionGranted(RC_READ_AND_WRITE_STORAGE)
    public void pickIcon() {
        if (hasReadAndWritePermissions()) {
            // Have permission, do the thing!
            Matisse.from(getActivity())
                    .choose(MimeType.ofAll(), false)
                    .countable(true)
                    .maxSelectable(1)
                    .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                    .thumbnailScale(0.85f)
                    .imageEngine(new Glide4Engine())
                    .forResult(REQUEST_CODE_CHOOSE);
            Toast.makeText(getActivity(), "TODO: Camera things", Toast.LENGTH_LONG).show();
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(
                    this,
                    getString(R.string.permissions_storage),
                    RC_READ_AND_WRITE_STORAGE,
                    READ_AND_WRITE_STORAGE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // EasyPermissions handles the request result.
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
        // This will display a dialog directing them to enable the permission in app settings.
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {

        }

    }
}
